package com.ruoyi.app.config.util;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.app.config.context.UserInfoContextHolder;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.service.user.model.UserInfoModel;

/**
 * <p>
 * 作用：用户信息工具
 * </p>
 *
 * @author Zane
 * @since 2025-10-02 7:51
 */
public class UserUtil {

  /**
   * 获取用户ID
   */
  public static Long getUserId() {
    return getLoginUser().getUserId();
  }

  /**
   * 获取用户名称
   */
  public static String getUsername() {
    return getLoginUser().getUserName();
  }

  /**
   * 获取登录用户信息
   */
  public static UserInfoModel getLoginUser() {
    return UserInfoContextHolder.getUserInfo();
  }

  /**
   * 获取登录用户信息可为空
   */
  public static UserInfoModel getLoginUserMayBeNull() {
    return UserInfoContextHolder.getUserInfoMayBeNull();
  }


  /**
   * 获取登录用户信息(脱敏)
   */
  public static UserInfoModel getLoginUserMasking() {
    final UserInfoModel userInfo = UserInfoContextHolder.getUserInfo();
    userInfo.setPhone(desensitize(userInfo.getPhone()));
    userInfo.setEmail(desensitize(userInfo.getEmail()));
    userInfo.setIdNumber(desensitize(userInfo.getIdNumber()));
    return userInfo;
  }

  public static String desensitize(String str) {
    if (StringUtils.isBlank(str)) {
      return str;
    }
    if (str.length() < 3) {
      return desensitize(str, 1, 2);
    }
    if (str.length() < 4) {
      return desensitize(str, 1, 2);
    }
    if (str.length() < 5) {
      return desensitize(str, 1, 3);
    }
    if (str.length() < 6) {
      return desensitize(str, 1, 3);
    }
    if (str.length() < 7) {
      return desensitize(str, 2, 4);
    }
    if (str.length() < 8) {
      return desensitize(str, 2, 5);
    }
    return replaceMiddle4(str);
  }

  private static String desensitize(String str, int startIndex, int endIndex) {
    final String s = StrUtil.padAfter(str.substring(0, startIndex), endIndex, "*");
    if (str.length() > endIndex) {
      return StrUtil.format("{}{}", s, str.substring(endIndex));
    }
    return s;
  }

  /**
   * 替换字符串中间4位为指定字符
   *
   * @param original 原始字符串
   * @return 处理后的字符串
   */
  public static String replaceMiddle4(String original) {
    // 计算需要保留的前后长度
    int keepLength = (original.length() - 4) / 2;
    // 处理长度为奇数的情况，让前半部分多保留1位
    if (original.length() % 2 != 0) {
      keepLength++;
    }
    // 构建替换后的字符串
    StringBuilder result = new StringBuilder();
    // 添加前半部分
    result.append(original.substring(0, keepLength));
    // 添加4位替换字符
    result.append("****");
    // 添加后半部分
    result.append(original.substring(keepLength + 4));
    return result.toString();
  }
}
